<?php
namespace app\api\controller;

use app\api\model\AdminUsers;
use think\facade\Cookie;


class User
{

    public function index()
    {
        return json(AdminUsers::find(1));
    }

    public function login()
    {
        $user_name = request()->param('user_name');
        $pwd = md5(request()->param('pwd'));

        $admin_user = AdminUsers::where('user_name', $user_name)->find();
        if(empty($admin_user)) return json([
            "status"=>403,
            'msg'=> '找不到用户',
        ], 403);

        
        $origin_pwd = $admin_user['pwd'];


        if($pwd != $origin_pwd){
            return json([
                'status'=> 403,
                'msg'=> "密码错误, $pwd, $origin_pwd"
            ], 403);
        }

        $admin_user['last_login_ip'] = get_real_ip();
        $admin_user['last_login'] = date("Y:m:d H-i-s", time());
        $admin_user->save();

        
        unset($admin_user['pwd'], $admin_user['last_login_ip']);
        
        $token=set_token($admin_user['user_name'], 'qzz');
        Cookie::set('tk', $token);
        Cookie::set('user', $admin_user);

        return json([
            'status'=> 200,
            'msg'=> '登陆成功'.$admin_user['user_name'],
            'user'=> $admin_user,
        ]);
    }

    public function logout()
    {
        Cookie::delete('tk');
        Cookie::delete('user');
        return true;
    }

    public function checkUserStatus()
    {
        $token = request()->param('tk');
        $user = (Array)json_decode(request()->param('user') );
        if(!check_token($token, $user['user_name'])){
            return json([
                'status'=>false
            ]);
        }
        return json([
            'status' => true,
            'user' => $user
        ]);
        
    }

    public function test()
    {
        return AdminUsers::find(1)['role'];
    }

    public function getAll()
    {
        return json(AdminUsers::select());
    }

    public function edit()
    {
        $data = request()->param();
        $user = AdminUsers::find($data['user_id']);
        return $user->save($data);
    }

    public function add()
    {
        $data = request()->param();
        $user = new AdminUsers;
        $data['pwd'] = md5($data['pwd']);
        $user->save($data);
        $id = $user['user_id'];
        unset($user);
        $user = AdminUsers::find($id);
        return json([
            'status'=> 'ok',
            'user' => $user,
        ]);
    }

    public function checkUserNameExits(){
        $user_name = request()->param('user_name');
        $user = AdminUsers::where('user_name', $user_name)->findOrEmpty();
        return json(['is_exits'=>!$user->isEmpty()]);
    }

    public function del() 
    {
        $user_id = request()->param('user_id');
        return AdminUsers::destroy($user_id);
    }
    
}
